import createAxiosClient from "@/app/utils/axiosRequest";
import ToastUtil from "@/app/utils/toastUtil";
import {Modal, ModalContent, ModalHeader, ModalBody, ModalFooter, Button} from "@nextui-org/react";
import PubSub from "pubsub-js";

/**
 * 删除文件夹
 * @param isOpenDelFolder
 * @param onOpenChangeDelFolder
 * @param folderId
 * @constructor
 */
export default function DelFolderService({isOpenDelFolder, onOpenChangeDelFolder, folderId}: any) {
    /*引入axios*/
    const axiosInstance = createAxiosClient();

    // 处理folderId：转换为数字类型
    const processedFolderId = folderId === 'root' || folderId === null ? null : Number(folderId);

    async function delFolder() {
        try {
            const response = await axiosInstance.delete(`/app/collection/${processedFolderId}`);
            const data = response.data;
            
            if (data.status) {
                ToastUtil(data.message || "删除成功", '🥰', "success");
                /*发布一个消息 用于更新列表*/
                PubSub.publish('refreshFolder', true);
                onOpenChangeDelFolder(false);
                return true;
            } else {
                ToastUtil(data.message || "删除失败", '😰', "error");
            }
        } catch (error: any) {
            ToastUtil(error.message || "操作异常", '🤒', "error");
        }
    }

    return (
        <>
            <Modal isOpen={isOpenDelFolder} onOpenChange={onOpenChangeDelFolder} isDismissable={false}
                   backdrop={"blur"} size="sm">
                <ModalContent>
                    {(onClose) => (
                        <>
                            <ModalHeader className="flex flex-col gap-1 dark:text-white light:text-black text-center">删除文件夹</ModalHeader>
                            <ModalBody>
                                <p className={`dark:text-white light:text-black text-center`}>
                                    确定删除该文件夹以及里面的所有内容吗？
                                </p>
                                <p className="text-danger text-sm text-center">此操作无法恢复，请谨慎操作！</p>
                            </ModalBody>
                            <ModalFooter className="flex justify-center gap-2">
                                <Button color="default" variant="flat" onPress={onClose}>
                                    取消
                                </Button>
                                <Button color="danger" onPress={delFolder}>
                                    确认删除
                                </Button>
                            </ModalFooter>
                        </>
                    )}
                </ModalContent>
            </Modal>
        </>
    )
}